<template>
  <div class="production-plan-detail">
    <div class="page-header">
      <h2>生产计划详情</h2>
    </div>

    <!-- 生产计划概览 -->
    <el-card class="overview-card" v-if="planDetail">
      <div class="plan-overview">
        <div class="plan-title">
          <h3>{{ planDetail.planSubject }}</h3>
        </div>
        <div class="plan-metadata">
          <div class="metadata-item">
            <span class="label">创建人:</span>
            <span class="value">{{ planDetail.creator }}</span>
          </div>
          <div class="metadata-item">
            <span class="label">创建时间:</span>
            <span class="value">{{ formatDateTime(planDetail.createTime) }}</span>
          </div>
          <div class="metadata-item">
            <span class="label">最后修改人:</span>
            <span class="value">{{ planDetail.updator }}</span>
          </div>
          <div class="metadata-item">
            <span class="label">修改时间:</span>
            <span class="value">{{ formatDateTime(planDetail.updateTime) }}</span>
          </div>
        </div>
        <div class="plan-actions">
          <el-button type="primary" @click="handleEdit">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" @click="handleDelete">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
          <el-button type="success" @click="handlePrint">
            <el-icon><Printer /></el-icon>
            打印
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 标签页 -->
    <el-card class="content-card">
      <el-tabs v-model="activeTab" type="card">
        <!-- 生产计划信息标签页 -->
        <el-tab-pane label="生产计划信息" name="info">
          <div class="tab-content">
            <!-- 基础信息 -->
            <div class="info-section">
              <h4>基础信息</h4>
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">计划单号:</span>
                    <span class="value">{{ planDetail?.planNumber }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">计划主题:</span>
                    <span class="value">{{ planDetail?.planSubject }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">单据日期:</span>
                    <span class="value">{{ formatDate(planDetail?.documentDate) }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">销售订单:</span>
                    <span class="value">{{ planDetail?.salesOrderId || '未绑定' }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">关联项目:</span>
                    <span class="value">{{ planDetail?.projectId || '未关联' }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">状态:</span>
                    <span class="value">{{ planDetail?.status }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <div class="info-item">
                    <span class="label">备注:</span>
                    <span class="value">{{ planDetail?.remarks || '无' }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>

            <!-- 生产物品 -->
            <div class="info-section">
              <div class="section-header">
                <h4>生产物品</h4>
                <el-button type="success" @click="exportItems">
                  <el-icon><Download /></el-icon>
                  导出
                </el-button>
              </div>
              <el-table :data="planDetail?.productedItems || []" border style="width: 100%" size="small">
                <el-table-column type="selection" width="45" />
                <el-table-column prop="index" label="序号" width="60" />
                <el-table-column prop="itemNumber" label="物品编号" width="120" />
                <el-table-column prop="itemName" label="物品名称" width="150" />
                <el-table-column prop="specificationModel" label="规格型号" width="120" />
                <el-table-column prop="unit" label="单位" width="80" />
                <el-table-column prop="itemCategory" label="物品类别" width="100" />
                <el-table-column prop="itemClassification" label="物品分类" width="100" />
                <el-table-column prop="brand" label="品牌" width="120" />
                <el-table-column prop="quantity" label="数量" width="80" />
                <el-table-column prop="detailDate" label="详情日期" width="100" />
                <el-table-column prop="mainUnitQuantity" label="主单位数量" width="100" />
                <el-table-column prop="remarks" label="备注" width="120" />
              </el-table>
              <div class="total-section">
                <span class="total-label">合计：</span>
                <span class="total-value">总量: {{ totalQuantity }}</span>
              </div>
            </div>

            <!-- 附件 -->
            <div class="info-section">
              <h4>附件</h4>
              <div v-if="planDetail?.attachments && planDetail.attachments.length > 0" class="attachments-grid">
                <div
                  v-for="(attachment, index) in planDetail.attachments"
                  :key="index"
                  class="attachment-card"
                >
                  <div class="attachment-icon">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="attachment-info">
                    <div class="file-name">{{ attachment.fileName }}</div>
                    <div class="file-size">文件大小: {{ formatFileSize(attachment.fileSize) }}</div>
                    <div class="upload-date">上传日期: {{ formatDateTime(attachment.uploadDate) }}</div>
                  </div>
                  <div class="attachment-actions">
                    <el-button type="primary" size="small" @click="viewAttachment(attachment)">
                      查看
                    </el-button>
                    <el-button type="success" size="small" @click="downloadAttachment(attachment)">
                      下载
                    </el-button>
                  </div>
                </div>
              </div>
              <div v-else class="no-attachments">
                <p>暂无附件</p>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 操作记录标签页 -->
        <el-tab-pane label="操作记录" name="logs">
          <div class="tab-content">
            <div class="section-header">
              <el-button type="success" @click="exportLogs">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
              <div class="search-box">
                <el-input
                  v-model="searchKeyword"
                  placeholder="请搜索"
                  clearable
                  style="width: 200px"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
            </div>
            
            <el-table :data="filteredLogs" border style="width: 100%" size="small">
              <el-table-column type="selection" width="45" />
              <el-table-column prop="index" label="序号" width="60" />
              <el-table-column prop="operator" label="操作人" width="120" />
              <el-table-column prop="operationTime" label="操作时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.operationTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="operationContent" label="操作内容" />
            </el-table>
            
            <div class="pagination-info">
              <span>共{{ filteredLogs.length }}项数据</span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Printer, Download, Document, Search } from '@element-plus/icons-vue'
import { getProductionPlanDetail, exportProductionPlanItems, exportProductionPlanLogs } from '@/services/productionPlan'
import type { ProductionPlanDetail, OperationLog } from '@/types/productionPlan'

const route = useRoute()
const router = useRouter()

// 响应式数据
const planDetail = ref<ProductionPlanDetail>()
const activeTab = ref('info')
const searchKeyword = ref('')
const loading = ref(false)

// 计算属性
const totalQuantity = computed(() => {
  if (!planDetail.value?.productedItems) return 0
  return planDetail.value.productedItems.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const filteredLogs = computed(() => {
  if (!planDetail.value?.operationLogs) return []
  if (!searchKeyword.value) return planDetail.value.operationLogs
  
  return planDetail.value.operationLogs.filter(log => 
    log.operator.includes(searchKeyword.value) ||
    log.operationContent.includes(searchKeyword.value)
  )
})

// 获取生产计划详情
const fetchPlanDetail = async () => {
  const id = Number(route.params.id)
  if (!id) {
    ElMessage.error('生产计划ID无效')
    return
  }

  loading.value = true
  try {
    const detail = await getProductionPlanDetail(id)
    planDetail.value = detail
  } catch (error: any) {
    ElMessage.error(error.message || '获取生产计划详情失败')
  } finally {
    loading.value = false
  }
}

// 导出生产物品
const exportItems = async () => {
  const id = Number(route.params.id)
  if (!id) return
  
  try {
    await exportProductionPlanItems(id)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 导出操作记录
const exportLogs = async () => {
  const id = Number(route.params.id)
  if (!id) return
  
  try {
    await exportProductionPlanLogs(id)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 编辑生产计划
const handleEdit = () => {
  const id = Number(route.params.id)
  router.push(`/edit-production-plan/${id}`)
}

// 删除生产计划
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个生产计划吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // TODO: 调用删除API
    ElMessage.success('删除成功')
    router.push('/production-plan')
  } catch (error) {
    // 用户取消删除
  }
}

// 打印生产计划
const handlePrint = () => {
  window.print()
}

// 查看附件
const viewAttachment = (attachment: any) => {
  // TODO: 实现附件查看功能
  ElMessage.info('附件查看功能开发中')
}

// 下载附件
const downloadAttachment = (attachment: any) => {
  // TODO: 实现附件下载功能
  ElMessage.info('附件下载功能开发中')
}

// 工具函数
const formatDate = (dateStr?: string) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleDateString()
}

const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const formatFileSize = (size: number) => {
  if (size === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(size) / Math.log(k))
  return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 初始化
onMounted(() => {
  fetchPlanDetail()
})
</script>

<style scoped>
.production-plan-detail {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.overview-card {
  margin-bottom: 20px;
}

.plan-overview {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.plan-title h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 18px;
}

.plan-metadata {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.metadata-item {
  display: flex;
  gap: 8px;
}

.metadata-item .label {
  color: #666;
  min-width: 80px;
}

.metadata-item .value {
  color: #333;
  font-weight: 500;
}

.plan-actions {
  display: flex;
  gap: 10px;
}

.content-card {
  margin-bottom: 20px;
}

.tab-content {
  padding: 20px 0;
}

.info-section {
  margin-bottom: 30px;
}

.info-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  margin-bottom: 15px;
}

.info-item .label {
  color: #666;
  min-width: 100px;
  font-weight: 500;
}

.info-item .value {
  color: #333;
}

.total-section {
  margin-top: 15px;
  text-align: right;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-label {
  color: #666;
  margin-right: 10px;
}

.total-value {
  color: #409eff;
  font-weight: 600;
  font-size: 16px;
}

.attachments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.attachment-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.attachment-icon {
  font-size: 24px;
  color: #409eff;
}

.attachment-info {
  flex: 1;
}

.file-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.file-size, .upload-date {
  font-size: 12px;
  color: #666;
  margin-bottom: 3px;
}

.attachment-actions {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.no-attachments {
  text-align: center;
  padding: 40px;
  color: #999;
}

.search-box {
  display: flex;
  align-items: center;
}

.pagination-info {
  margin-top: 15px;
  text-align: right;
  color: #666;
}

@media print {
  .plan-actions,
  .section-header,
  .attachment-actions {
    display: none;
  }
}
</style> 